import Home from "@renderer/pages/Home";
import About from "@renderer/pages/About";
import { MenuProps } from "antd";
import { HomeOutlined } from "@ant-design/icons";
import AppLayout from "@renderer/App";
import Dev from "@renderer/pages/Dev";
import ServiceList from "@renderer/pages/ServiceList";
import { HashRouter, Route, Routes } from "react-router";
import QrCode from "@renderer/pages/QrCode";
import Base64 from "@renderer/pages/base64";

type MenuItem = Required<MenuProps>['items'][number];

type RouteObjectPlus = {
  path?: string;
  label?: string;
  icon?: React.ReactNode;
  element?: React.ReactNode;
  children?: RouteObjectPlus[];
};

const menuRoutes: RouteObjectPlus[] = [
  {
    path: "home",
    label: "主页",
    element: <Home />,
    icon: <HomeOutlined />,
  },
  {
    path: "about",
    label: "关于",
    element: <About />,
  },
  {
    path: "server",
    label: "服务列表",
    element: <ServiceList />,
  },
  {
    path: "Dev",
    label: "开发者",
    element: <Dev />,
  },
  {
    path: "utils",
    label: "工具",
    children: [
      {
        path: "utils/qrCode",
        label: "二维码解析",
        element: <QrCode />,
      },
      {
        path: "utils/base64",
        label: "base64转码",
        element: <Base64 />,
      },
    ],
  },
];

// 生成菜单项
const processRoutes = (items: RouteObjectPlus[], parentPath = ''): MenuItem[] => {
  return items.map(item => {
    const fullPath = parentPath ? `${parentPath}/${item.path}` : item.path;
    const menuItem: any = {
      key: fullPath || `${parentPath}-${item.label}`,
      label: item.label,
    } as MenuItem;

    if (item.icon) {
      menuItem.icon = item.icon;
    }

    if (item.children) {
      menuItem.children = processRoutes(item.children, fullPath || parentPath);
    }

    return menuItem;
  });
};

export const menuItems: MenuItem[] = processRoutes(menuRoutes);

// 创建路由组件
export const AppRoutes = () => (
  <Routes>
    <Route path="/" element={<AppLayout />}>
      <Route index element={<Home />} />
      {menuRoutes.map((route) => (
        <Route key={route.path} path={route.path} element={route.element}>
          {route.children?.map((child) => (
            <Route
              key={child.path}
              path={child.path}
              element={child.element}
            />
          ))}
        </Route>
      ))}
    </Route>
  </Routes>
);

// 在应用的根组件中使用
export const AppWithRouter = () => (
  <HashRouter>
    <AppRoutes />
  </HashRouter>
);
